/*
 * 网络类，处理客户端和服务器间的通讯
 */
package com.rainfull.core;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;  

import com.rainfull.util.json.HTTP;
import com.rainfull.util.json.JSONArray;
import com.rainfull.util.json.JSONException;
import com.rainfull.util.BASE64;
import com.rainfull.util.HttpUtil;
import com.rainfull.util.json.JSONObject;

public class RNetworkProcess
{  	   
	private static String Trim(String str)
	{
		if (str.length() > 1 &&str.charAt(0) == '\"' && str.charAt(str.length() - 1) == '\"')
		{
			str = str.substring(1, str.length() - 1);
		}
		return str;
	}
   /*
    * 账号注册
    */
   public static RUserInfo userReg(String strUserName, String strPwd)
   {  		
	   strUserName = new String(BASE64.encode(strUserName.getBytes()));
	   RUserInfo userInfo = new RUserInfo();
	   boolean bRet = false;		   		   
	   String strJson = "{user_name:\"" + strUserName +"\", pwd:\""+ strPwd +"\"}";
	   String strRet = HttpUtil.PostInfo(Config.strUrlReg, strJson);
	   //检测返回数据合法性
	   if (strRet == null || strRet.length() == 0)
	   {
		   return userInfo;
	   }	
	   try
	   {
		   JSONObject obj = new JSONObject(strRet);
		   int nResult = Integer.parseInt(obj.get("result").toString());
		   if (nResult > 0)
		   {
			   strUserName = (String)obj.get("user_name");
			   String strToken = (String)obj.get("token");
			   //解决中文问题
			   strUserName = new String(BASE64.decode(strUserName.toCharArray()));
		       Integer nScore = Integer.parseInt(obj.get("score").toString());
			   userInfo.setUserName(strUserName);
			   userInfo.setToken(strToken);
			   userInfo.setScore(nScore);
		   }
	   }
	   catch(Exception e)
	   {			   
		   e.printStackTrace();			   
	   }		   
	   return userInfo;
   }
   /*
    * 账号登陆
    */
   public static RUserInfo userLoginEx(String strToken)
   {
	   String strJson = "{token:\"" + strToken +"\"}";
	   return userLoginByJson(strJson);
   }
   public static RUserInfo userLogin(String strUserName, String strPwd)
   {
	   strUserName = new String(BASE64.encode(strUserName.getBytes()));
	   String strJson = "{user_name:\"" + strUserName +"\", pwd:\""+ strPwd +"\"}";
	   return userLoginByJson(strJson);
   }
   private static RUserInfo userLoginByJson(String strJson)
   {  		
	   RUserInfo userInfo = new RUserInfo();
	   String strRet = HttpUtil.PostInfo(Config.strUrlLogin, strJson);
	   //检测返回数据合法性
	   if (strRet == null || strRet.length() == 0)
	   {
		   return userInfo;
	   }	
	   try
	   {
		   JSONObject obj = new JSONObject(strRet);
		   int nResult = Integer.parseInt(obj.get("result").toString());
		   if (nResult > 0)
		   {
			   String strUserName = (String)obj.get("user_name");
			   strUserName = new String(BASE64.decode(strUserName.toCharArray()));
			   String strToken = (String)obj.get("token");
			   Integer nScore = Integer.parseInt(obj.get("score").toString());				   				   
			   userInfo.setUserName(strUserName);
			   userInfo.setScore(nScore);
			   userInfo.setToken(strToken);
		   }
	   }
	   catch(Exception e)
	   {			   
		   e.printStackTrace();			   
	   }		   
	   return userInfo;
   }	   
   /*
    *通过服务器上传ap密码等用户信息,
   	*返回 发送的url信息，已经当前用户分数
    */	   
   public static RUploadApResult upLoadSvrApPwd(String strToken, int nShare, RAPItemInfo apItemInfo)
   {  				   
	   //updateApPosInfo(apItemInfo);
	   RUploadApResult retRet = new RUploadApResult(); 
	   boolean bRet = false;		   		   
	   String strPwd = apItemInfo.getPwd();
	   strPwd = Trim(strPwd);
	   String strSSID = apItemInfo.getSSID();
	   strSSID = Trim(strSSID);
	   String strJson = "{token:\""+strToken+",ssid:" + strSSID + "\",share:"+nShare+",mac:\"" + apItemInfo.getBSSID() +"\", pwd:\""+strPwd+"\"";
	   strJson += ",la:" + apItemInfo.getLatitude() +", lo:"+apItemInfo.getLongitude()+"}";
	   String strRet = HttpUtil.PostInfo(Config.strUrlUploadApInfo, strJson);
	   String strPostInfo = "";
	   try
	   {
		   strPostInfo = strJson;
	   }
	   catch(Exception e)
	   {
		  
	   }
	   retRet.setUrlUpLoad(strPostInfo); 
	   //检测返回数据合法性
	   if (strRet == null || strRet.length() == 0)
	   {			   
		   return retRet;
	   }	
	   try
	   {
		   JSONObject obj = new JSONObject(strRet);		   
		   if (obj.has("result"))
		   {
			   bRet = true;
			   int nScore = Integer.parseInt(obj.get("score").toString());
			   if (nScore == -1)
				   nScore = -2;
			   retRet.setUserScore(nScore);
		   }			   
	   }
	   catch(Exception e)
	   {			   
		   e.printStackTrace();			   
	   }		   
	   return retRet;
   }
   //通过服务器获取ap密码等用户信息
   public static boolean getApPwdFromSvr(String strToken, List<RAPItemInfo> APList)
   {  		
	   boolean bRet = false;
	   String strJson = "{token=\""+ strToken +"\", mac_list:[";			
	   int nSize = APList.size();
	   boolean bAdd = false;
	   for(int i = 0; i < nSize; i++)
	   {
		   RAPItemInfo itemInfo = APList.get(i);
		   if(itemInfo.isOpenAp() == false)
		   {
			   if (bAdd == true)			   
			   {
				   strJson += ",";
			   }
			   bAdd = true;
			   strJson += "{mac:\"" + itemInfo.getBSSID() +"\"}";
		   }
	   }	
	   strJson +="]}";			   
	   String strRet = HttpUtil.PostInfo(Config.strUrlGetApPwd, strJson);
	   //检测返回数据合法性
	   if (strRet == null || strRet.length() == 0)
	   {
		   return false;
	   }	
	   try
	   {
		   JSONArray objArray = new JSONArray(strRet); 			   		   
		   int nLen = objArray.length();		  
		   for(int i = 0; i < nLen; i++)		   
		   {
			   JSONObject obj = objArray.getJSONObject(i);
			   String strBSSID = obj.getString("mac");
			   String strPwd = obj.getString("pwd");
			   for(int j = 0; j < APList.size(); j++)
			   {
				   RAPItemInfo itemInfo = APList.get(i);
				   if (itemInfo.getBSSID().equals(strBSSID))
				   {
					   itemInfo.setPwd(strPwd);
					   break;
				   }
			   }
			   
		   }
	   }
	   catch(Exception e)
	   {
		   e.printStackTrace();			   
	   }		   
	   //strJson = "{  'version': '1.1.0',  'host': 'maps.google.com',  'access_token': '2:k7j3G6LaL6u_lafw:4iXOeOpTh1glSXe',  'home_mobile_country_code': 310,  'home_mobile_network_code': 410,  'radio_type': 'gsm',  'carrier': 'Vodafone',  'request_address': true,  'address_language': 'zh_CN',  'wifi_towers': [    {      'BSSID_address': '"+"1c:af:f7:89:24:c6"+ "',      'signal_strength': 8,      'age': 0    },     ]}";		        			
	   //String strRet = HttpUtil.PostInfo(strUrl, strJson);
	   return bRet;
   }  
   	/*
    * 更新ap位置信息,经纬度
    */
    public static boolean updateApListPosInfo(List<RAPItemInfo> APList) 
	{
    	boolean bRet = false;
    	int nSize = APList.size();
    	for(int i = 0; i < nSize; i++)
    	{
    		boolean bRetTemp = updateApPosInfo(APList.get(i));
    		if (bRet == true)
    			bRet = bRetTemp;
    	}
    	return bRet;
	}
    /*
    * 更新ap位置信息,经纬度
    */
    public static boolean updateApPosInfo(RAPItemInfo mapItemInfo)
    {
		boolean bRet = false;			
		try
		{	
			if(mapItemInfo.getLatitude() != 0.0 &&
					mapItemInfo.getLongitude() != 0.0)
			{
				return true;
			}
			
			String strUrl = "http://www.google.com/loc/json";
			String content = "{  'version': '1.1.0',  'host': 'maps.google.com',  'access_token': '2:k7j3G6LaL6u_lafw:4iXOeOpTh1glSXe',  'home_mobile_country_code': 310,  'home_mobile_network_code': 410,  'radio_type': 'gsm',  'carrier': 'Vodafone',  'request_address': true,  'address_language': 'zh_CN',  'wifi_towers': [    {      'BSSID_address': '"+mapItemInfo.getBSSID()+ "',      'signal_strength': 8,      'age': 0    },     ]}";		        
			String strRet = HttpUtil.PostInfo(strUrl, content);
			if (strRet.length() > 0)
		    {
				JSONObject obj = new JSONObject(strRet);			    
			    obj = obj.getJSONObject("location");
			    if (obj.has("latitude"))
			    {
			    	mapItemInfo.setLatitude(new Double(obj.getString("latitude")));
			    	mapItemInfo.setLongitude(new Double(obj.getString("longitude")));	
			    	bRet = true;
			    }
			    if (obj.has("address"))
			    {
			    	obj = obj.getJSONObject("address");
			    	String strCity = obj.getString("city");
			    	String street = obj.getString("street");
			    	mapItemInfo.setStrAddress(strCity+street);
			    	mapItemInfo.setLatitude(new Double(obj.getString("latitude")));
			    	mapItemInfo.setLongitude(new Double(obj.getString("longitude")));	
			    	bRet = true;
			    }
		    }
		}
		catch(Exception e)
		{
			
		}
		return bRet;
	}
    /*
     * 通过ap的坐标获取周围的ap信息
     */
    public static void getApListByPos(int nLa, int nLo)
    {
		
	}
}  